/*
*Copyright (c) Nikhil Jain.
*Project ICARUS, communications and 
*artificial intelligence.
*/



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package javadrone.client.simulation;

//~--- non-JDK imports --------------------------------------------------------

import javadrone.Drone;

import javadrone.agent.ExtendedAgent;

import javadrone.command.*;

import javadrone.statedata.ErrorData;

import simbad.sim.Agent;
import simbad.sim.CameraSensor;
import simbad.sim.RobotFactory;

//~--- JDK imports ------------------------------------------------------------

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.rmi.RemoteException;

import javax.vecmath.Vector3d;

/**
 *
 * @author Nikzzay
 */
public class AgentSimulator extends Agent {
    private BotSimulator    bs;
    private CameraSensor    camera;
    private BufferedImage   cameraImage;
    private CommandExecutor ce;
    private Drone           drone;
    private boolean         startStreamFlag;

    public AgentSimulator(BotSimulator bs, Drone drone, CommandExecutor ce, Vector3d pos, String name) {
        super(pos, name);
        camera      = RobotFactory.addCameraSensor(AgentSimulator.this);
        cameraImage = camera.createCompatibleImage();
        this.bs     = bs;
        this.drone  = drone;
        this.ce     = ce;
    }

    public void performBehaviour() {
        System.out.println("In...");

        Command c;

        try {
            if (bs.isAlive()) {
                if (collisionDetected()) {
                    ce.raiseCollisionFlag();
                }

                if (startStreamFlag) {
                    camera.copyVisionImage(cameraImage);
                }

                while ((c = drone.pollCommand()) != null) {
                    System.out.println("COMMAND EXECUTED: " + c);
                    c.execute(ce);
                }
            } else if ((c = drone.pollCommand()).getDescriptor().equals(CommandDescriptor.BOOTSTRAP)) {
                c.execute(ce);
                System.out.println("Booted... " + bs.isAlive());
            } else {
                ce.raiseError(ErrorData.ErrorState.ErrorFlag.BOOT_NOT_READY_ERROR);
                System.out.println("Bot not ready...");
            }
        } catch (ExecutorException ex) {}
        catch (RemoteException e) {
            ce.raiseError(ErrorData.ErrorState.ErrorFlag.CONNECTION_ERROR);
        } catch (NullPointerException npe) {
            ce.raiseError(ErrorData.ErrorState.ErrorFlag.EMPTY_COMMAND_QUEUE_ERROR);
            System.out.println("Empty command queue...");
        } catch (IOException e) {
            ce.raiseError(ErrorData.ErrorState.ErrorFlag.IMAGE_READ_ERROR);
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
